<?php

namespace app\admin\controller;

use app\common\controller\Backend;


/**
 * 广告位管理
 *
 * @icon fa fa-circle-o
 */
class Adsense extends Backend
{
    
    /**
     * Adsense模型对象
     * @var \app\admin\model\Adsense
     */
    protected $model = null;


    protected $beforeActionList=[
        'index_delAll'=>['only'=>'index_del'],
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Adsense;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
//广告位列表
    public function index(){

        $list=db("adsense")->where("p_id=0")->field("*")->select();
        $this->assign("list",$list);
        return $this->view->fetch();
    }
//广告位添加
    public function index_add(){
        $adsense=db("adsense");
        if(request()->isPost()){
            $data=input('post.');
            $add=$adsense->insert($data);
            if($add){
                $res=$adsense->order("id desc")->find();
                $adsense->where("id","{$res['id']}")->setField('adno', "{$res['id']}");
                $this->success("广告位添加成功",'index');
            }else{
                $this->error("广告位添加失败");
            }
        }

        return $this->view->fetch();
    }
//广告位修改
    public function index_edit(){
        $adsense=db("adsense");
        $id=input("id");
        $res=$adsense->field("*")->find($id);
        if(request()->isPost()){
            $data=input("post.");
            $update=$adsense->update($data);
            if($update){
                $this->success("广告位修改成功",'index');
            }else{
                $this->error("广告位修改失败");
            }
        }
        $this->assign([
            'res'=>$res,
        ]);
        return $this->view->fetch();
    }
//广告位删除   广告删除未做
    public function index_del(){
        $adsense=db("adsense");
        $id=input("id");
        $res=$adsense->delete($id);
        if($res){
            $this->success("广告位删除成功",'index');
        }else{
            $this->error("广告位删除失败");
        }
    }

    public function index_delAll(){
        $ad=db("ad");
        $id=input("id");
        $list=$ad->where("sense_id",$id)->select();
        if($list){
            foreach($list as $k=>$v){
                $ad->delete($v['id']);
            }
        }

    }

//广告列表
    public function index_ad(){
        $ad=db("ad");
        $sense_id=input("id");
        $list=db("ad")
            ->alias("a")
            ->join("adsense s","a.sense_id=s.id")
            ->field("a.*,s.adtype,s.adtitle")
            ->where("a.sense_id",$sense_id)
            ->order("ad_order desc")
            ->select();
        if(request()->isPost()){
            $data_order=input("post.");
            foreach ($data_order as $k=>$v){
                $ad->where("id",$k)->setField("ad_order",$v);
            }
            $this->success("排序修改成功");
        }
        $product=db("product")->field("id,s_name")->select();
        $this->assign([
            'list'=>$list,
            'sense_id'=>$sense_id,
            'product'=>$product,
        ]);

        return $this->view->fetch();
    }

    public function index_ad_product_select(){
        $sense_id=input("sense_id");
        $product=db("product")->field("id,s_name")->order("id desc")->paginate(5,false, ['query' => $this->request->param()]);
        $this->assign([
            'sense_id'=>$sense_id,
            'product'=>$product,
        ]);

        return $this->view->fetch();
    }



    public function uploadImg($str){
        ///  /./ dump($str);
          /// die;
           $file = request()->file($str);
           $filePaths = ROOT_PATH . 'public' . DS . 'uploads' . DS ;
           if(!file_exists($filePaths)){
               mkdir($filePaths,0777,true);
           }
           $info = $file->move($filePaths);
           // dump($info);
           if($info){
               $imgpath = $info->getPath()."/".$info->getBasename();//物理路径
               $image = \think\Image::open($imgpath);
               $date_path = $info->getPath()."/"."200".'_'."120";
               $imgpath=$info->getSaveName();//原图上传  路径： 日期/文件名
               if(!file_exists($date_path)){
                   mkdir($date_path,0777,true);
               }
               $thumb_path = $date_path.'/'."1-".$info->getBasename();
               $image->thumb(200, 120)->save($thumb_path);
               $data['m_path'] = "/uploads/".$imgpath;
               return $data;
           }else{
               // 上传失败获取错误信息
               return $file->getError();
           }
       }



    //广告添加  --自定义上传图片
    public function index_ad_add(){
        $ad=db("ad");
        $sense_id=input("sense_id");
        $res=db("adsense")->find($sense_id);
        if(request()->isPost()){
            $data=input('post.');
            $data['sense_id']=$sense_id;

          if($sense_id == 70){
            if($_FILES['pic']['tmp_name']){
                $str="pic";
                $img=$this->uploadImg($str);
                $data['imgurl']=str_replace('\\','/',$img['m_path']);
            }
          }else{
           
           if($data['imgurl']!=''){
               $img=base64_image_content($data['imgurl']);
               //dump($a);
               $data['imgurl']=$img['url'];
           }
        }
        
            
            $add=$ad->insert($data);
            if($add){
                $this->success("广告添加成功","/admin/adsense/index_ad?id={$sense_id}");
            }else{
                $this->error("广告添加失败");
            }
        }
        $this->assign([
           'sense_id'=>$sense_id,
            'res'=>$res,
        ]);
        return $this->view->fetch();
    }

    public function index_ad_product_add(){
        $data=input("get.");
        $main=request()->domain();
        $url=$main."/index/show/detail?id={$data['id']}";
        $res=db("product")->find($data['id']);
        $resAd=db("adsense")->find($data['sid']);
        if(request()->isPost()){
            $datap=input("post.");
           /// dump($datap);
            $datap['p_id']=$data['id'];
            $datap['sense_id']=$data['sid'];
            if($datap['imgurl']!=''){
                $img=base64_image_content($datap['imgurl']);
                $datap['imgurl']=$img['url'];
            }

            $add=db("ad")->insert($datap);
            if($add){
                $this->success("广告添加成功","/admin/adsense/index_ad?id={$data['sid']}");
            }else{
                $this->error("广告添加失败");
            }
        }

        $this->assign([
            'res'=>$res,
            'sense_id'=>$data['sid'],
            'resAd'=>$resAd,
            'url'=>$url,
        ]);
        return $this->view->fetch();
    }


    //广告修改
    public function index_ad_edit(){
        $ad=db("ad");
        $id=input("id");
        
        $res=$ad->find($id);
        $resAd=db("adsense")->find($res['sense_id']);
        if(request()->isPost()){
            $data=input("post.");
            $home_post = input("post.home_post");
            $show_post = input("post.show_post");
            if($res['sense_id'] == 70){
                if($_FILES['pic']['tmp_name']){
                    $str="pic";
                    $img=$this->uploadImg($str);
                    $data['imgurl']=str_replace('\\','/',$img['m_path']);
                }
            }else{

                if($data['imgurl']!=''){
                    if(preg_match("/upload/i",$data['imgurl'])){
                        $data['imgurl']=$res['imgurl'];
                    }else{
                        if($res['imgurl']!=''){
                            $img_url=ROOT_PATH . 'public'.$res['imgurl'];
                            @unlink($img_url);
                        }
                        $img=base64_image_content($data['imgurl']);
                        $data['imgurl']=$img['url'];
                    }
                }else{
                    if($res['imgurl']!=''){
                        $img_url=ROOT_PATH . 'public'.$res['imgurl'];
                        @unlink($img_url);
                    }
                    $data['imgurl']='';
                }


            }
            if($home_post){
                $data['home_post']=input("post.home_post");
            }else{
                $data['home_post'] = 0;
            }

            if($show_post){
                $data['show_post']=input("post.show_post");
            }else{
                $data['show_post'] = 0;
            }
            

           // dump($data);die;
            $update=$ad->update($data);//update 方法返回影响数据的条数，没修改任何数据返回 0
            if($update){
                $this->success("广告修改成功","/admin/adsense/index_ad?id={$res['sense_id']}");
            }else{
                $this->error("广告修改失败");
            }
        }
        $this->assign([
            'res'=>$res,
            'resAd'=>$resAd,
            'sense_id'=>$res['sense_id'],
        ]);

        return $this->view->fetch();
    }

    //广告删除

    public function index_ad_del(){
        $ad=db("ad");
        $id=input("id");
        $resAd=$ad->find($id);
        $res=$ad->delete($id);
        if($res){
            $this->success("广告删除成功","/admin/adsense/index_ad?id={$resAd['sense_id']}");
        }else{
            $this->error("广告删除失败");
        }
    }

}
